package io.gitee.thant.utils;

import java.util.ArrayList;
//import java.util.LinkedList;
//import java.util.Iterator;
import java.util.List;

public class ByteBuilder {
	//private List<byte[]> _lst = new LinkedList<byte[]>();
	private List<byte[]> _lst = new ArrayList<byte[]>(); //比LinkedList快
	private int _sz = 0;
	
	public ByteBuilder append(byte[] data) {
		if (null != data && data.length>0) {
			_lst.add(data);
			_sz += data.length;
		}
		return this;
	}

	public ByteBuilder append(byte b) {
		return append(new byte[]{b});
	}

	public ByteBuilder append(String data, String encode) {
		byte[] ba = null;
		try {
			ba = (null==encode) ? data.getBytes() : data.getBytes(encode);
		} catch (Exception e) { }
		return append(ba);
	}
	
	public byte[] toArrayRef() {
		setLength(_sz);
		return _lst.get(0);
	}
	
	public ByteBuilder setLength(int len) {
		if (len>=0) {
			byte[] target = new byte[len];
			
			/*//LinkedList要用Iterator，不要用get
			int p=0;
			Iterator<byte[]> it = _lst.iterator();
			while (p<len && it.hasNext()) {
				byte[] ba = it.next();
				if (p+ba.length<len) {
					System.arraycopy(ba, 0, target, p, ba.length);
					p += ba.length;
				} else {
					System.arraycopy(ba, 0, target, p, len-p);
					p += len-p;
				}
			}*/
			//ArrayList
			for(int i=0, p=0; p<len && i<_lst.size(); ++i) {
				byte[] ba = _lst.get(i);
				if (p+ba.length<len) {
					System.arraycopy(ba, 0, target, p, ba.length);
					p += ba.length;
				} else {
					System.arraycopy(ba, 0, target, p, len-p);
					p += len-p;
				}
			}
			
			_lst.clear();
			_lst.add(target);
			_sz = len;
		}
		return this;
	}
	
	public int size() {
		return _sz;
	}
}
